import { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, DatePicker, Select, message } from 'antd';
import { getBookData,getRoomData, addCustomer } from '@/request/api'
import type { ColumnsType } from 'antd/es/table';
import BkState from './components/State'
import RoomType from './components/RoomType'
const { Search } = Input;
const { RangePicker } = DatePicker;
const rangeConfig = {
  rules: [{ type: 'array' as const, required: true, message: 'Please select time!' }],
};

const App: React.FC = () => {

  const [bkData, setBkData] = useState([])
  const [roomData, setRoomData] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false) //控制弹窗
  const [totle, setTotle] = useState(1)
  const [pageSize] = useState(7) //分页条数
  const [temp, setTemp] = useState("") //搜索

  const [form] = Form.useForm(); //定义form

  useEffect(() => {
    getData()
  },[])


  const columns: ColumnsType<BookingDataType> = [
    {
      title: '编号',
      dataIndex: 'bkId',
      key: 'bkId',
    },
    {
      title: '姓名',
      dataIndex: 'bkName',
      key: 'bkName',
    },
    {
      title: '电话',
      dataIndex: 'bkPhone',
      key: 'bkPhone',
    },
    {
      title: '提交时间',
      key: 'bkSumbitDate',
      dataIndex: 'bkSumbitDate',
    },
    {
      title: '预定开始时间',
      key: 'bkBeginDate',
      dataIndex: 'bkBeginDate',
    },
    {
      title: '预定结束时间',
      key: 'bkEndDate',
      dataIndex: 'bkEndDate',
    },
    {
      title: '预定状态',
      key: 'bkState',
      dataIndex: 'bkState',
      render: (_, record) => <BkState state={record.bkState} />,
    },
    {
      title: '房间类型',
      key: 'roomType',
      dataIndex: 'roomType',
      render: (_, record) => <RoomType type={record.roomType} />,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        return (
          record.bkState == 1 ?
            <Button type="primary" onClick={() => showModal(record)} size='small'>办理入住</Button> :
            <BkState state={record.bkState} />
        )
      }
    },
  ]


  const getData = async (pageNum: number = 1, search:string = "") => {
    const { data, code } = await getBookData({ pageNum, pageSize, search})

    if (code == 0) {
      setTotle(data.total)
      setBkData(data.records)
      const roomdata:NoPageReq = await getRoomData()
      setRoomData(roomdata.data)
    }
  }

  const showModal = (data: BookingDataType) => {
    
    //更新输入框的值
    form.setFieldsValue({
      name: data.bkName,
      phone: data.bkPhone,
      cardId: "",
      time: "",
      bkId: data.bkId,
      roomId: ""
    })
    setIsModalOpen(true);
  }


  const onFinish = async (values: FieldType2) => {
    const timeValue: any[] = values.time
    const room:any = roomData.find((item: roomDataType) => item.roomId == values.roomId)
    
    const params:RoomRes = {
      ...values,
      beginDate: timeValue[0].format('YYYY-MM-DD'), //入住时间
      endDate: timeValue[1].format('YYYY-MM-DD'), //退房时间
      roomPrice: room.roomPrice, //房间单价
      totalAmount: room.roomPrice * Math.trunc((timeValue[1] - timeValue[0]) / (1000 * 3600 * 24)) //总价格
    }
    const { code } = await addCustomer(params)
    if(code == 0){
      getData()
      message.success({ content: "登记成功！", duration: 3 })
    }
    setIsModalOpen(false);
  };

  const onSearch = (value:string) => {
    setTemp(value)
    getData(1, value)
  } 

  return (
    <>
      <div style={{width: '300px', margin: '20px 20px 20px 0'}}>
        <Search placeholder="请输入预定的客户姓名" onSearch={onSearch} enterButton allowClear/>
      </div>
      <Table columns={columns} dataSource={bkData} rowKey="bkId" pagination={
        {
          total: totle,//数据的总条数
          defaultCurrent: 1,//默认当前的页数
          defaultPageSize: pageSize,//默认每页的条数
          onChange: (page: number) => getData(page, temp)
        }
      } />

      <Modal title="入住登记" open={isModalOpen} footer={null} onCancel={() => setIsModalOpen(false)}>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="预定编号"
            name="bkId"
            rules={[{ required: true, message: '预定编号不能为空!' }]}
          >
            <Input readOnly/>
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '姓名不能为空!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="电话"
            name="phone"
            rules={[{ required: true, message: '电话不能为空!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="身份证"
            name="cardId"
            rules={[{ required: true, message: '身份证号码不能为空!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="房间号"
            name="roomId"
            rules={[{ required: true, message: '身份证号码不能为空!' }]}
          >
            <Select>
              {roomData.map((item: roomDataType) => {
                if(item.roomState === 0){
                  return(
                    <Select.Option value={item.roomId} key={item.roomId}>
                      {item.roomId + "--￥" + item.roomPrice}
                    </Select.Option>
                    )
                }
              })}
            </Select>
          </Form.Item>
          <Form.Item name="time" label="入住时间" {...rangeConfig}>
            <RangePicker showTime format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
};

export default App;
